package com.binance.notification.data.configs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binance.master.annotations.DefaultDB;
import com.binance.master.data.DBConfig;
import com.binance.master.data.sharding.TableRuleSharding;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;


@Configuration
@PropertySource(value="classpath:config/db-${spring.profiles.active}.properties",ignoreResourceNotFound = true)
@MapperScan(basePackages = "com.binance.notification.data", annotationClass = DefaultDB.class,
        sqlSessionFactoryRef = "sqlSessionFactory")
public class DefaultDBConfig extends DBConfig {

    @Override
    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() throws SQLException {
        JSONObject datas = JSON.parseObject(this.env.getProperty("hikaricp.data", String.class));
        return this.dataSource(datas, super.applicationContext.getBeansOfType(TableRuleSharding.class));
    }

    @Primary
    @Bean(name = DefaultDB.TRANSACTION)
    @Override
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        DataSourceTransactionManager dstm = super.transactionManager(dataSource);
        return dstm;
    }

    @Primary
    @Bean(name = "sqlSessionFactory")
    @Override
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        return super.sqlSessionFactory(dataSource);
    }
}
